package com.example.onlinemonitoring.serviceImpl;

import com.example.onlinemonitoring.model.Oilsensor;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Oilconfig;
import com.example.onlinemonitoring.model.Oilhistory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jca.cci.core.RecordExtractor;
import org.springframework.stereotype.Service;
import com.example.onlinemonitoring.Util.tem.SensorAbstractBaseService;
import com.example.onlinemonitoring.dao.OilconfigMapper;
import com.example.onlinemonitoring.service.OilsensorService;

import net.bytebuddy.implementation.bind.annotation.Super;
import tk.mybatis.mapper.entity.Example;

import com.example.onlinemonitoring.model.common.MyResult;
import com.example.onlinemonitoring.model.common.chartres;
import com.example.onlinemonitoring.model.common.pagebase;
import com.example.onlinemonitoring.query.QueryObject;
import com.example.onlinemonitoring.Util.ConditionDispose;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.Util.LanguageManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description Oilsensor接口实现
 * @author generator
 * @since 2022-04-09 13:03:09
 */
@Service("oilServiceImpl")
public class OilsensorServiceImpl extends SensorAbstractBaseService<Oilsensor, Oilhistory> implements OilsensorService {
    @Autowired
    OilconfigMapper oilconfigmapper;
    @Autowired
    LanguageManager languageManager;
    @Value("${OILWINDOW.wstart}")
    String wstart = "850,1050,1500,3000,5200,6600,9100,0,0,0";
    @Value("${OILWINDOW.wend}")
    String wend = "1050,1350,2000,4000,6300,7500,10200,0,0,0";

    public int Update(Oilconfig record, Boolean byid) {
        if (byid)
            return oilconfigmapper.updateByPrimaryKeySelective(record);
        else
            return oilconfigmapper.updateByExampleSelective(record,
                    ConditionDispose.defaultDisposeByUpdate(record, record.getClass()));
    }

    public int Add(Appdevice record) {
        String[] addrarray = record.getSubswitch().split(",");
        for (String addrstr : addrarray) {
            String[] gasstr = new String[] { "H2", "CO", "CH4", "CO2", "C2H4", "C2H6", "C2H2", "O2", "N2", "H2O" };
            String start[] = wstart.split(",");
            String end[] = wend.split(",");
            Oilconfig oc = new Oilconfig();
            oc.setStationid(record.getStationid());
            oc.setDevicegroup(record.getDevicegroup());
            oc.setDeviceaddr(Integer.parseInt(addrstr));
            Delete(oc);
            for (int j = 0; j < 10; j++) {
                oc.setGas(gasstr[j]);
                if (j == 3) {
                    oc.setCof1(10f);
                } else {
                    oc.setCof1(1f);
                }
                oc.setCof2(1f);
                oc.setCof3(1f);
                oc.setCof4(1f);
                oc.setPcof1(0f);
                oc.setPcof2(0f);
                oc.setPcof3(0f);
                oc.setPcof4(0f);
                oc.setHeight1(200f);
                oc.setHeight2(300f);
                oc.setHeight3(400f);
                oc.setHeight4(500f);
                oc.setStart(Float.parseFloat(start[j]));
                oc.setEnd(Float.parseFloat(end[j]));
                Add(oc);
            }
        }
        int ret = 1;
        for (String addrstr : addrarray) {
            Oilsensor sensor = new Oilsensor();
            Example example = new Example(Oilsensor.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stationid", record.getStationid());
            criteria.andEqualTo("devicegroup", record.getDevicegroup());
            criteria.andEqualTo("deviceaddr", Integer.parseInt(addrstr));
            sensor.setPointname(languageManager.getLan().getNewMonitoringPoint());
            sensor.setStyle(languageManager.getLan().getStyleOil());
            sensor.setDeviceaddr(Integer.parseInt(addrstr));
            sensor.setStationid(record.getStationid());
            sensor.setDevicegroup(record.getDevicegroup());
            sensor.setLastcommunicationstatus(-1);
            sensor.setLastdatatime(new Date());
            sensor.setLastalarmlevel(0);
            sensor.setLastalarmmessage("");
            sensor.setMemo("");
            sensor.setInuse(1);
            if (selectOneByExample(example) == null) {
                if (insertSelective(sensor) == 0) {
                    ret = 0;
                }
            }
        }
        return ret;
    }

    public int Add(Oilconfig record) {
        return oilconfigmapper.insertSelective(record);
    }

    public void UpdateStyle(String style) {
        List<Oilsensor> list = selectAll();
        if (list.size() <= 0) {
            return;
        }
        String old_style = list.get(0).getStyle();
        StringBuilder newStyleBuilder = new StringBuilder();
        String[] parts = style.split(",");
        String[] oldParts = old_style.split(",");
        for (int i = 0; i < parts.length; i++) {
            String[] newkeyValue = parts[i].split("\\|");
            String[] oldkeyValue = oldParts[i].split("\\|");

            newStyleBuilder.append(oldkeyValue[0] + "|" + oldkeyValue[1] + "|" + newkeyValue[2]);
            newStyleBuilder.append(",");
        }

        // 移除最后一个逗号
        if (newStyleBuilder.charAt(newStyleBuilder.length() - 1) == ',') {
            newStyleBuilder.setLength(newStyleBuilder.length() - 1);
        }
        Oilsensor record = new Oilsensor();
        record.setStyle(newStyleBuilder.toString());
        Update(record, false);
    }

    public int Delete(Oilconfig record) {
        Example example = new Example(Oilconfig.class);
        Example.Criteria criteria = example.createCriteria();
        if (record.getStationid() != null) {
            criteria.andEqualTo("stationid", record.getStationid());
        }
        if (record.getDevicegroup() != null) {
            criteria.andEqualTo("devicegroup", record.getDevicegroup());
        }
        if (record.getDeviceaddr() != null) {
            criteria.andEqualTo("deviceaddr", record.getDeviceaddr());
        }
        return oilconfigmapper.deleteByExample(example);
    }

    public MyResult<Oilconfig> getList(Oilconfig record) {
        List<Oilconfig> list = oilconfigmapper
                .selectByExample(ConditionDispose.defaultDispose(record, record.getClass()));
        MyResult<Oilconfig> result = new MyResult<Oilconfig>();
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list != null && !list.isEmpty() ? list.size() : 0);
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg(languageManager.getLan().getDataEmpty());
        }
        return result;
    }

    /**
     * 更新运行状态
     * 
     * @param ad
     * @param addr
     * @param b
     */
    public void UpdateStatus(Appdevice ad, Integer addr, int b) {
        Oilsensor record = new Oilsensor();
        record.setStationid(ad.getStationid());
        record.setDevicegroup(ad.getDevicegroup());
        record.setLastcommunicationstatus(b);
        record.setDeviceaddr(addr);
        Update(record, false);
    }

    public MyResult<float[][]> getPuerperalRate(Oilhistory record, pagebase pagebase) {
        MyResult<float[][]> res = new MyResult<>();
        List<float[][]> list = new ArrayList<>();
        MyResult<Oilhistory> oilhis = getHisList(record, pagebase);
        Oilsensor oil = new Oilsensor();
        oil.setStationid(record.getStationid());
        oil.setDevicegroup(record.getDevicegroup());
        oil.setDeviceaddr(record.getDeviceaddr());
        oil = getModel(oil);
        float[][] data = new float[2][];
        data[0] = new float[8];
        data[1] = new float[8];
        list.add(data);
        res.setData(list);
        if (oilhis.getData() == null) {
            res.setCode(1);
            res.setMsg(languageManager.getLan().getMsg1());
            return res;
        }
        if (oilhis.getData().size() < 2) {
            res.setCode(1);
            res.setMsg(languageManager.getLan().getMsg2());
            return res;
        }
        if (oil == null) {
            res.setCode(1);
            res.setMsg(languageManager.getLan().getMsg3());
            return res;
        }
        if (oil.getQuality() == null) {
            res.setCode(1);
            res.setMsg(languageManager.getLan().getMsg4());
            return res;
        }
        if (oil.getDensity() == null) {
            res.setCode(1);
            res.setMsg(languageManager.getLan().getMsg5());
            return res;
        }
        Oilhistory today = oilhis.getData().get(0);
        Oilhistory yesterday = oilhis.getData().get(oilhis.getData().size() - 1);
        Oilhistory lastday = oilhis.getData().get(oilhis.getData().size() - 1);
        float volume = oil.getQuality() / oil.getDensity();// 油体积
        data[0][0] = (today.getH2() - yesterday.getH2()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;
        data[0][1] = (today.getCo() - yesterday.getCo()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;
        data[0][2] = (today.getCh4() - yesterday.getCh4()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;
        data[0][3] = (today.getCo2() - yesterday.getCo2()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;
        data[0][4] = (today.getC2h4() - yesterday.getC2h4()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;
        data[0][5] = (today.getC2h6() - yesterday.getC2h6()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;
        data[0][6] = (today.getC2h2() - yesterday.getC2h2()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;
        data[0][7] = (today.getTothyd() - yesterday.getTothyd()) * 86400000l
                / (today.getDatatime().getTime() - yesterday.getDatatime().getTime()) * volume;

        data[1][0] = (today.getH2() - lastday.getH2()) / lastday.getH2()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        data[1][1] = (today.getCo() - lastday.getCo()) / lastday.getCo()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        data[1][2] = (today.getCh4() - lastday.getCh4()) / lastday.getCh4()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        data[1][3] = (today.getCo2() - lastday.getCo2()) / lastday.getCo2()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        data[1][4] = (today.getC2h4() - lastday.getC2h4()) / lastday.getC2h4()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        data[1][5] = (today.getC2h6() - lastday.getC2h6()) / lastday.getC2h6()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        data[1][6] = (today.getC2h2() - lastday.getC2h2()) / lastday.getC2h2()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        data[1][7] = (today.getTothyd() - lastday.getTothyd()) / lastday.getTothyd()
                * (2592000000l / (today.getDatatime().getTime() - lastday.getDatatime().getTime())) * 100;
        list.add(data);
        res.setData(list);
        res.setCode(0);
        res.setMsg(languageManager.getLan().getOperationSuccess());
        return res;
    }
}
